package com.naiterui.ehp.bp.support.utils;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.extra.servlet.ServletUtil;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import com.naiterui.ehp.bp.constants.CommonConstant;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IpUtil {

    private static final File DBFILE = IpUtil.getDbfile();

    /**
     * 获取ip地址
     */
    public static String getIp(HttpServletRequest request) {
        return ServletUtil.getClientIP(request);
    }

    /**
     * 根据ip获取详细地址
     */
    public static String getCityInfo(String ip) {
        DbSearcher searcher = null;
        try {
            DbConfig config = new DbConfig();
            searcher = new DbSearcher(config, DBFILE.getPath());
            DataBlock dataBlock = searcher.btreeSearch(ip);
            String address = dataBlock.getRegion().replace("0|", "");
            char symbol = '|';
            if (address.charAt(address.length() - 1) == symbol) {
                address = address.substring(0, address.length() - 1);
            }
            return address.equals(CommonConstant.REGION) ? "内网IP" : address;
        } catch (Exception e) {
            log.warn("获取地址失败 {}", ip, e);
        } finally {
            if (searcher != null) {
                try {
                    searcher.close();
                } catch (IOException ignored) {
                }
            }

        }
        return "";
    }

    private static File getDbfile() {
        if (IpUtil.DBFILE == null) {
            synchronized (IpUtil.class) {
                try {
                    return FileUtil.inputStreamToFile(new ClassPathResource("ip2region/ip2region.db").getStream(), "ip2region.db");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return IpUtil.DBFILE;
    }

}
